// index.js
Page({
  /* ================== 数据 ================== */
  data: {
    newsList: [],
    tabs: [],          // 分类
    activeIndex: 0,    // 当前选中下标
    activeCatId: 0,    // 当前分类 id
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  /* ================== 生命周期 ================== */
  onLoad() {
    this.loadCategory();   // 先拉分类
  },

  /* 下拉刷新 */
  onPullDownRefresh() {
    this.loadNews(true);
  },

  /* 上拉加载更多 */
  onReachBottom() {
    this.loadNews(false);
  },

  /* ================== 网络请求 ================== */
  // 获取分类
  loadCategory() {
    wx.request({
      url: 'https://tea.qingnian8.com/api/qingnews/category',
      method: 'GET',
      header: { 'access-key': 272690 },
      success: (res) => {
        const tabs = res.data.data || [];
        this.setData({ tabs, activeCatId: tabs[0]?.id || 0 }, () => {
          this.loadNews(true);   // 默认拉第 1 个分类
        });
      }
    });
  },

  // 获取新闻（带分类 id 的分页）
  loadNews(isRefresh = false) {
    if (this.data.loading) return;
    if (!isRefresh && !this.data.hasMore) return;

    this.setData({ loading: true });
    const page = isRefresh ? 1 : this.data.page;

    wx.request({
      url: 'https://tea.qingnian8.com/api/qingnews/newslist',
      method: 'GET',
      header: { 'access-key': 272690 },
      data: {
        page,
        pagesize: this.data.pageSize,
        cid: this.data.activeCatId   // 关键：分类 id
      },
      success: (res) => {
        const list = res.data.data || [];
        const total = res.data.total || 0;

        const newsList = isRefresh
          ? list
          : this.data.newsList.concat(list);

        this.setData({
          newsList,
          page: isRefresh ? 2 : this.data.page + 1,
          hasMore: newsList.length < total,
          loading: false
        });
        wx.stopPullDownRefresh();
      },
      fail: () => {
        this.setData({ loading: false });
        wx.stopPullDownRefresh();
      }
    });
  },

  /* ================== 事件 ================== */
  // 点击分类
  onTabClick(e) {
    const index = e.currentTarget.dataset.index;
    const catId = this.data.tabs[index].id;
    this.setData({ activeIndex: index, activeCatId: catId }, () => {
      this.loadNews(true);   // 切换后重新下拉
    });
  },

// 进入详情 + 浏览记录（带 3 行落地日志）
goDetail(e) {
  console.log('>>> 事件对象', e);                          // ① 整个事件
  console.log('>>> dataset', e.currentTarget.dataset);     // ② dataset 全貌
  const aid = Number(e.currentTarget.dataset.id);
  console.log('>>> 转换后 id', aid);                       // ③ 最终值
  const current = this.data.newsList.find(item => item.id == aid);
  if (!current) {
    console.log('>>> 没找到对象，直接 return');
    return;
  }

  // 浏览记录
  const history = wx.getStorageSync('historyNews') || [];
  history.unshift({
    id: current.id,
    title: current.title,
    picurl: current.picurl,
    author: current.author,
    hits: current.hits,
    browseTime: Date.now()
  });
  wx.setStorageSync('historyNews', history);

  // 收藏（去重）
  const saved = wx.getStorageSync('savedNews') || [];
  if (!saved.some(v => v.id === aid)) {
    saved.unshift({
      id: current.id,
      title: current.title,
      picurl: current.picurl,
      author: current.author,
      hits: current.hits
    });
    wx.setStorageSync('savedNews', saved);
  }

  wx.navigateTo({ url: `../detail/detail?id=${aid}` });
},

  /* ================== 其余生命周期 ================== */
  onHide() {},
  onUnload() {},
  onShareAppMessage() {}
});